<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use App\Admin\Models\Product;
use App\Admin\Models\Common;
use App\Admin\Models\storeGoodsOut;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Ixudra\Curl\Facades\Curl;
use DB;

class ProductController extends Controller
{
	use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('商品')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('产品')
            ->description('详细')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('产品')
            ->description('编辑')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('产品')
            ->description('新增')
            ->body($this->form());
    }

//  public function update(Request $request, $id)
//  {
//
//  }

//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {
//
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Product);
        $grid->sgId('ID');
        $grid->sgName('产品名称');
        $grid->sgLogo('产品图片')->image(50, 50);
        $grid->sgPrice('产品价格');
        $grid->sgNum('库存');
        $grid->createTime('上传时间');

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});

		$grid->actions(function ($actions) {
		    $actions->disableDelete();
//		    $actions->disableEdit();
//		    $actions->disableView();
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		    $filter->column(1/2, function ($filter) {

		    	$filter->like('sgName', '产品名称');

			});

		});

		// 默认展开筛选框
		$grid->expandFilter();

		// 禁用行选择checkbox
		$grid->disableRowSelector();

		// 禁用导出
		$grid->disableExport();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Product = new Product();
        $show = new Show($Product->findOrFail($id));

        $show->sgId('ID');
        $show->sgName('产品名称');
        $show->sgLogo('产品图片');
        $show->sgDesc('产品描述');
        $show->sgPrice('产品单价');
        $show->dpId('分销规则');
		$Common = new Common();
		$dpSelect = $Common->getPreceptSelect();
        $show->dpId('分销规则')->using($dpSelect);
        $show->sgNum('库存');
        $show->sgWarningNum('库存警报数量');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');
		$show->sgIsChaffer('议价')->using(['1' => '是','0' => '否'])->value('1');
		$show->panel()
			->tools(function ($tools) {
//				$tools->disableEdit();
//				$tools->disableList();
				$tools->disableDelete();
		});;
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id=false)
    {
    	$isCard = true;
    	if ($id){
    		$goodsInfo = DB::table('store_goods')->where('sgId', $id)->first();
    		$isCard = $goodsInfo->sgIsTimeCard;
    	}

        return Admin::Form(Product::class, function (Form $form) use($isCard, $id) {

            $sId = Admin::user()->sId;

            $form->tab('基础信息', function ($form) use($sId, $id) {
                $form->hidden('sgId');
                $form->text('sgName', '产品名称')->rules("required", ['required' => '请填写产品名称']);
                // $form->image('sgLogo', '产品图片')->removable()->uniqueName()->rules("required", ['required' => '请填写产品图片']);
                $form->image('sgLogo', '产品图片')->removable()->uniqueName();
                //$form->textarea('sgDesc', '产品描述');
                $form->UEditor('sgDesc', '产品描述')->options(['initialFrameHeight' => 300])->rules("required", ['required' => '请填写产品描述']);

                if ($id){
                    // 不知道为什么查询构建器获得的结果不对
                    // $agpList = DB::table('agency_goods_price')
                    //                 ->selectRaw(' agency_goods_price.alLevel, agency_level.alId, agency_level.alName, agency_goods_price.goodsPrice')
                    //                 ->leftJoin('agency_level', function ($leftJoin) {
                    //                         $leftJoin->on('agency_goods_price.acId', '=', 'agency_level.acId')
                    //                                  ->where('agency_goods_price.alLevel', '=', 'agency_level.alLevel');
                    //                     })
                    //                 ->where('agency_goods_price.acId', $sId)
                    //                 ->where('agency_goods_price.goodsId', $id)
                    //                 ->orderBy('agency_goods_price.alLevel', 'DESC')
                    //                 ->get();

                    $agpList = DB::select("SELECT
	agency_goods_price.alLevel,
	agency_level.alId,
	agency_level.alName,
	agency_goods_price.goodsPrice
FROM
	`agency_goods_price`
	LEFT JOIN `agency_level` ON `agency_goods_price`.`acId` = `agency_level`.`acId`
	AND `agency_goods_price`.`alLevel` = agency_level.alLevel
WHERE
	`agency_goods_price`.`acId` = ?
	AND `agency_goods_price`.`goodsId` = ?
ORDER BY
	`agency_goods_price`.`alLevel` DESC", [$sId, $id]);
// print_r(\json_encode($agpList));exit;
                    if (count($agpList) > 0){
                        $form->fieldset('各个等级对应单价', function (Form $formPrice) use($agpList) {
                            foreach($agpList as $agpInfo){
                                $formPrice->currency('sgPrice_'.$agpInfo->alLevel, $agpInfo->alName)->symbol('￥')->default($agpInfo->goodsPrice);
                            }
                        });
                    }else{
                        $alList = DB::table('agency_level')->where('acId', $sId)->orderBy('alLevel', 'DESC')->get();
                        if (count($alList) > 0){
                            $form->fieldset('各个等级对应单价', function (Form $formPrice) use($alList) {
                                foreach($alList as $alInfo){
                                    $formPrice->currency('sgPrice_'.$alInfo->alLevel, $alInfo->alName)->symbol('￥');
                                }
                            });
                        }else{
                            $form->currency('sgPrice', '产品单价')->symbol('￥');
                        }
                    }
                }else{
                    $alList = DB::table('agency_level')->where('acId', $sId)->orderBy('alLevel', 'DESC')->get();
                    if (count($alList) > 0){
                        $form->fieldset('各个等级对应单价', function (Form $formPrice) use($alList) {
                            foreach($alList as $alInfo){
                                $formPrice->currency('sgPrice_'.$alInfo->alLevel, $alInfo->alName)->symbol('￥');
                            }
                        });
                    }else{
                        $form->currency('sgPrice', '产品单价')->symbol('￥');
                    }
                }

                $Common = new Common();
                $dpSelect = $Common->getPreceptSelect();

                $form->select('dpId', '分销规则')->options($dpSelect)->help('请到【商品管理】->【分销管理】进行分销规则创建和维护');

            })->tab('卡项或服务', function ($form) {
                $states = [
                    'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
                    'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
                ];
                // 卡项 ///////////////////////////////////////////////////////////////////////////////////////////////
                $script = <<<EOT

var sgIsTimeCard = state ? 1 : 0;
if (sgIsTimeCard == 1){
    $('.dpId').parent().parent().show();
    $('.sgTimeCardNum').parent().parent().parent().parent().show();
    $('.sgYearCard').parent().parent().show();
    // $('.sgIsIncludeService').parent().parent().show();
    // $('.sgServiceMoney').parent().parent().parent().parent().show();
    $('.include').parent().parent().parent().parent().parent().parent().parent().show();
    $('.include').parent().parent().parent().parent().parent().parent().show();
}else{
    $('.dpId').parent().parent().hide();
    $('.sgTimeCardNum').parent().parent().parent().parent().hide();
    $('.sgIsIncludeService').parent().parent().hide();
    $('.sgYearCard').parent().parent().hide();
    $('.sgServiceMoney').parent().parent().parent().parent().hide();
    $('.include').parent().parent().parent().parent().parent().parent().parent().hide();
}

EOT;

                $form->switch('sgIsTimeCard', '是否为卡包或服务')
                     ->states($states)
                     ->setInjectJs($script)
                     ->default(0)
                     // ->readonly()
                     ->help('即不可统计库存的商品或服务，如理发卡，按摩卡这种可无限量发放');

                $form->select('sgYearCard', '年卡或月卡')
                     ->options(['0'=>'否', '1'=>'年卡', '2'=>'月卡'])
                     ->default(0)
                     ->help('卡项的有效期为一年或一月');
                $form->number('sgTimeCardNum', '可使用次数')->default(10);
                $form->switch('sgIsIncludeService', '是否每次使用需支付额外费用')
                     ->states($states)
                     ->default(0);
                $form->number('sgServiceMoney', '每次使用额外费用')
                     ->default(0)
                     ->help('比如购买一盒10支美容针，每次来打针需要另外支付服务费50元给美容师');

                // 卡项 ///////////////////////////////////////////////////////////////////////////////////////////////

                $StoreGoodsOut = new StoreGoodsOut();
                $productData = $StoreGoodsOut->getStoreGoodsList();

                // $form->table('include', '包含的商品', function ($form) use($productData) {
                //     $form->select('sgId', '名称')->options($productData);
                //     $form->number('sgNum', '数量')->default(1);
                // });

            })->tab('扩展信息', function ($form) {
                // 添加删除按钮removable
                $form->multipleImage('sgPicList', '产品相册')->removable()->uniqueName()->sortable()->help('请一次上传多张图片，重复上传会覆盖前面已上传的图片');
                $form->number('sgWarningNum', '库存警报数量')->default('10')->attribute(['style' => 'width: 150px;']);
                $form->radio('sgIsChaffer', '是否可以议价')->options(['0' => '否', '1'=> '是'])->default(1);
            });

            $script =  <<<EOT

// $('.dpId').parent().parent().hide();
$('.sgTimeCardNum').parent().parent().parent().hide();
$('.sgIsIncludeService').parent().parent().hide();
$('.sgYearCard').parent().parent().hide();
$('.sgServiceMoney').parent().parent().parent().hide();
$('.include').parent().parent().parent().parent().parent().parent().parent().hide();
EOT;
            Admin::script($script);

			//$form->select('sId','店铺')->options('/store/getList');

			//保存前回调
			$form->saving(function (Form $form) {

			    if ($form->sgId){
			    	$info = DB::table('store_goods')
			    				->where('sId', Admin::user()->sId)
			    				->where('sgName', $form->sgName)
			    				->where('sgId', '<>', $form->sgId)
			    				->first();

			    }else{
			    	$info = DB::table('store_goods')
			    				->where('sId', Admin::user()->sId)
			    				->where('sgName', $form->sgName)
			    				->first();
			    }
			    if ($info){
			    	$error = new MessageBag([
                        'title'   => '错误',
                        'message' => '该商品名称已存在，请修改商品名称！',
                    ]);

                    return back()->with(compact('error'))->withInput();
			    }
			});

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});
        });
    }
}
